package cn.bnjy.controller;

import cn.bnjy.common.EasyData;
import cn.bnjy.common.WeiXinApi;
import cn.bnjy.common.WeiXinConstant;
import cn.bnjy.core.Result;
import cn.bnjy.entity.Address;
import cn.bnjy.entity.Invite;
import cn.bnjy.service.IAddressService;
import cn.bnjy.service.IInviteService;
import cn.bnjy.util.DateUtils;
import cn.bnjy.util.HttpUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * 描述：年会涨粉活动
 *
 * @author chavin
 * @since 2018-12-16 20:18:41
 */
@RequestMapping("/activity/")
@Controller
@Slf4j
public class ActivityController {

    @Autowired
    private IAddressService addressService;

    @Autowired
    private IInviteService inviteService;

    /**
     * 活动首页
     * @return
     */
    @RequestMapping("home")
    public String activityHome(HttpServletRequest request, Model model) {
        String activityStartTime = EasyData.CONFIG_MAP.get("ActivityStartTime");
        String activityEndTime = EasyData.CONFIG_MAP.get("ActivityEndTime");
        if(DateUtils.between(new Date(), activityStartTime, activityEndTime)) {
            String code = request.getParameter("code");
            if(StringUtils.isBlank(code)) {
                model.addAttribute("type", "0");
            } else {
                String result = HttpUtils.post(WeiXinApi.WEIXIN_WEB_OAUTH2_USER_INFO.replace("APPID", EasyData.CONFIG_MAP.get(WeiXinConstant.APPID)).replace("SECRET", EasyData.CONFIG_MAP.get(WeiXinConstant.APPSECRET)).replace("CODE", code), "");
                if(StringUtils.isNotBlank(result)) {
                    JSONObject object = JSONObject.parseObject(result);
                    if(object != null && object.containsKey("openid")) {
                        String openId = String.valueOf(object.get("openid"));
                        HttpSession session = request.getSession();
                        session.setAttribute(WeiXinConstant.OPEN_ID, openId);
                        QueryWrapper<Invite> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("invite_open_id", openId).groupBy("invite_open_id");
                        int cnt = inviteService.count(queryWrapper);
                        int step1 = Integer.parseInt(EasyData.CONFIG_MAP.get("ActivityStep1"));
                        if(cnt >= step1) {
                            model.addAttribute("type", "1");  // 尚未达到奖励
                        } else {
                            model.addAttribute("type", "0");  // 尚未达到奖励
                        }
                    }
                }
            }
        } else {
            model.addAttribute("type", "-1");  // 活动已结束
        }
        return "activity/activity-addr";
    }

    /**
     * 跳转获奖填写地址页面，并判断当前用户是否已完成任务
     * @param response
     * @throws IOException
     */
    @GetMapping(value="auth")
    public void webAuth(HttpServletResponse response) throws IOException {
        String url = EasyData.CONFIG_MAP.get("DOMAIN") + "/activity/home";
        String redirectUrl = WeiXinApi.WEIXIN_WEB_SNSAPI_BASE_AUTH.replace("APPID", EasyData.CONFIG_MAP.get(WeiXinConstant.APPID)).replace("REDIRECT_URI", URLEncoder.encode(url, WeiXinConstant.UTF8));
        response.sendRedirect(redirectUrl);
    }

    /**
     * 保存获奖地址
     * @param address
     * @param request
     * @return
     */
    @PostMapping(value="saveAddress")
    @ResponseBody
    public Result saveAddress(Address address, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String openId = String.valueOf(session.getAttribute(WeiXinConstant.OPEN_ID));
        if(StringUtils.isBlank(openId)) {
            return Result.error("获取用户信息失败");
        }
        address.setOpenId(openId);
        address.setCreateTime(new Date());
        return addressService.save(address) ? Result.success("保存成功") : Result.error("保存失败");
    }

}
